<template>
  <el-form :model="form" label-width="120px">
    <el-form-item label="学生学号">
      <el-select v-model="form.student_id" @change="getStudentInfo" disabled >
        <el-option v-for="cls in students" :key="cls.student_id" :label="cls.student_name" :value="cls.student_id"/>
      </el-select>
    </el-form-item>
    <el-form-item label="姓名">
      <el-input v-model="form.name" disabled/>
    </el-form-item>
    <el-form-item label="奖惩名称">
      <el-input v-model="form.reward_name" />
    </el-form-item>
    <el-form-item label="奖惩类型">
      <el-radio-group v-model="form.reward_type">
        <el-radio label="奖励">奖励</el-radio>
        <el-radio label="惩罚">惩罚</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="奖惩日期">
      <el-date-picker
          v-model="form.reward_date"
          type="date"
          placeholder="选择日期"
      />
    </el-form-item>
    <el-form-item label="备注">
      <el-input v-model="form.remark" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm() ">确认修改</el-button>
      <el-button @click="closeDialog() ">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import RewardApi from '@/api/RewardApi';

export default {
  props: {
    currentReward: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      form: {
        student_id: '',
        name: '',
        reward_name: '',
        reward_type: '',
        reward_date: '',
        remark: '',
      },
      studentsId: [] // 学号列表

    };
  },
  methods: {
    submitForm() {
      this.$emit('submit-form',this.form);
    },
    closeDialog() {
      this.$emit('close-dialog');
    },
    getStudentInfo(student_id) {
      this.initialStudetId_change= false; // 标记为已修改
      const selectedStudent = this.studentsId.find(cls => cls.student_id === student_id);
      if (selectedStudent) {
        this.form.name = selectedStudent.name;
      }
    },
    async fetchStudents() {
      try {
        //获得一个学号，学号中包含姓名
        const response = await RewardApi.getStudentsForm();
        this.studentsId = response.data.data || response.data;
        console.log(this.studentsId);
      } catch (error) {
        console.error("学号姓名信息获取错误:", error);
      }
    }
  },
  watch: {
    // 监听父组件传入的currentReward变化
    currentReward: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          // 将父组件传入的学生数据填充到表单中
          this.form = {
            student_id: newVal.student_id,
            name: newVal.name,
            reward_name: newVal.reward_name,
            reward_type: newVal.reward_type,
            reward_date: newVal.reward_date,
            remark: newVal.remark,
          }
        }
      }
    }
  },
  created() {
    this.fetchStudents();
  }
};
</script>
